package LinkedQueues;

import java.util.Iterator;

public class LinkedQueue<E> implements QueueInterface<E>,Iterable<E>{
    private int size;
    private final int capacity = 10;


    static class Node<E> {
        public E value;
        public Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    Node<E> hand = new Node<>(null,null);
    Node<E> tail = hand;

    public LinkedQueue() {
        tail.next = hand;
    }


    @Override
    public boolean offer(E value) {

        if (isOverflow()) {
            System.out.println("容量不足！！！");
            return false;
        }
        Node<E> addFirst = new Node<>(value,hand);
        tail.next = addFirst;
        tail = addFirst;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            System.out.println("链表已经为空！！！");
            return null;
        }
        Node<E> remove = hand.next;
        hand.next = remove.next;
        size--;
        if (tail == remove) {
            tail = hand;
        }
        return remove.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            System.out.println("已经为空链表！！！");
            return null;
        }
        return hand.next.value;
    }

    @Override
    public boolean isEmpty() {
        return hand == tail;
    }

    @Override
    public boolean isOverflow() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = hand.next;
            @Override
            public boolean hasNext() {
                return p != hand;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

}
